<template>
  <div class="qs-y-table-card">
    <el-table v-loading="listLoading" border :data="list" :row-class-name="tableRowClassName" stripe>
      <el-table-column align="center" label="序号" width="55">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>

      <el-table-column
        v-for="(item, index) in finallyColumns"
        :key="index"
        align="center"
        :fixed="item.fixed"
        :label="item.label"
        :min-width="item.minWidth || 150"
        show-overflow-tooltip
        :sortable="item.sortable"
      >
        <template #default="{ row }">
          <template v-if="item.slotName">
            <slot :name="item.slotName" :row="row"></slot>
          </template>
          <template v-else-if="item.component">
            <component
              :is="item.component"
              v-bind="
                item.componentProps ? (typeof item.componentProps === 'function' ? item.componentProps(row) : item.componentProps) : {}
              "
              :model-value="formatColumnValue(row, item)"
              :row="row"
            />
          </template>
          <template v-else>
            <span v-if="item.prop">
              <template v-if="item.dictionary">
                {{ item.dictionary[getNestedValue(row, item.prop)] || getNestedValue(row, item.prop) || '-' }}
              </template>
              <template v-else>
                {{ getNestedValue(row, item.prop) || '-' }}
              </template>
            </span>
            <span v-else>-</span>
          </template>
        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="操作" width="120">
        <template #default="{ row }">
          <el-button :disabled="row.isCheck || row.isLeave" link type="primary" @click="handleSignIn(row)">
            {{ row.isCheck ? '已签到' : row.isLeave ? '已请假' : '签到' }}
          </el-button>
        </template>
      </el-table-column>

      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>

    <el-pagination
      background
      :current-page="currentPage"
      :layout="layout"
      :page-size="pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
  </div>
</template>

<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed } from 'vue'
import type { TableColumn } from '../config'
import type { Person } from '../types'

const props = defineProps<{
  list: Person[]
  listLoading: boolean
  finallyColumns: TableColumn[]
  layout: string
  total: number
  queryForm: {
    page: number
    limit: number
    [key: string]: any
  }
}>()

const emit = defineEmits<{
  (e: 'update:queryForm', value: any): void
  (e: 'handleSizeChange', value: number): void
  (e: 'handleCurrentChange', value: number): void
  (e: 'signIn', userId: string): void
}>()

const currentPage = computed({
  get: () => props.queryForm.page,
  set: (val) => emit('update:queryForm', { ...props.queryForm, page: val }),
})

const pageSize = computed({
  get: () => props.queryForm.limit,
  set: (val) => emit('update:queryForm', { ...props.queryForm, limit: val }),
})

// 工具函数
const getNestedValue = (obj: any, path: string) => {
  const value = path.split('.').reduce((acc, part) => {
    return acc && acc[part] !== undefined ? acc[part] : null
  }, obj)
  return value === null || value === undefined ? '-' : value
}

const formatColumnValue = (row: any, item: TableColumn) => {
  const value = getNestedValue(row, item.prop)
  console.log('formatColumnValue:', {
    prop: item.prop,
    rawValue: value,
    hasFormat: !!item.format,
    formattedValue: item.format ? item.format(row) : value,
  })
  if (item.format) {
    return item.format(row)
  }
  if (item.component === 'Tags' && Array.isArray(value)) {
    return value.map((tag: any) => tag.value)
  }
  return value
}

const handleSizeChange = (val: number) => {
  emit('handleSizeChange', val)
}

const handleCurrentChange = (val: number) => {
  emit('handleCurrentChange', val)
}

// 处理签到
const handleSignIn = async (row: Person) => {
  if (row.isLeave) {
    ElMessage.warning('已请假人员无法签到')
    return
  }
  try {
    await ElMessageBox.confirm('确认进行签到操作？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    })
    emit('signIn', row.userId)
  } catch (error) {
    if (error !== 'cancel') {
      console.error(error)
      ElMessage.error('签到失败')
    }
  }
}

// 表格行样式
const tableRowClassName = ({ row }: { row: Person }) => {
  if (row.isLeave) {
    return 'leave-row'
  }
  return ''
}
</script>

<style scoped>
.qs-y-table-card {
  padding: 20px;
  background-color: var(--el-bg-color);
  border-radius: 4px;
}

.el-pagination {
  justify-content: flex-end;
  margin-top: 15px;
}

:deep(.vab-data-empty) {
  padding: 30px 0;
}

/* 使用更深的红色以便区分，并确保覆盖默认样式 */
/* :deep(.el-table .leave-row) {
  background-color: #fff0f0 !important;
}

:deep(.el-table .leave-row:hover > td) {
  background-color: #ffeded !important;
} */
</style>
